﻿#!/usr/bin/env python
#coding=utf-8
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import cgi
import wsgiref.handlers
import os
from google.appengine.api import users
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.db import GqlQuery
from google.appengine.ext.webapp.util import run_wsgi_app

from urllib2 import urlopen
from urllib import urlencode
import md5
from google.appengine.api import urlfetch

class Admob(webapp.RequestHandler):
  def get(self):
    template_values = {}
    data = my_view(self.request)
    #path = os.path.join(os.path.dirname(__file__), 'game.html')
    #self.response.out.write(template.render(path, template_values))
    self.response.out.write(data)

def my_view(request):

    admob_dict = {}
    admob_dict["admob_site_id"] = "a14c89dd10abe93"
    admob_dict["admob_postal_coode"] = "optional_postal_code"
    admob_dict["admob_area_code"] = "optional_area_code"
    admob_dict["admob_coordinates"] = "optional_coordinates"
    admob_dict["admob_gender"] = "male"
    admob_dict["admob_keywords"] = "mario"
    admob_dict["admob_search"] = "optional_search"		
    
    ad = admob_ad(request, admob_dict)
    
    return HttpResponse(ad)

def admob_ad(request, admob_params=None):
	"""
	Given a Django ``request`` object and dict of
	admob parameters returns a Admob ad.
	
	If no ad can be retrieved displays a one pixel
	Admob tracker image.
	
	Usage:
	
	def my_view(request):
	
		admob_dict = {}
		admob_dict["admob_site_id"] = "required_admob_site_id"
		admob_dict["admob_postal_coode"] = "optional_postal_code"
		admob_dict["admob_area_code"] = "optional_area_code"
		admob_dict["admob_coordinates"] = "optional_coordinates"
		admob_dict["admob_gender"] = "optional_gender"
		admob_dict["admob_keywords"] = "optional_keywords"
		admob_dict["admob_search"] = "optional_search"		
		
		ad = admob_ad(request, admob_dict)
		
		return HttpResponse(ad)
	
	"""
	# Change to "live" when ready to deploy.
	admob_mode = "test"
	
	admob_endpoint = "http://r.admob.com/ad_source.php"
	admob_version = "20080714-PYTHON"
	admob_timeout = 1.0
	admob_ignore = ("HTTP_PRAGMA", "HTTP_CACHE_CONTROL", "HTTP_CONNECTION", "HTTP_USER_AGENT", "HTTP_COOKIE",)

	# Build URL.
	admob_post = {} 
	
	# Required Parameters - will raise if not found.
	admob_post["s"] = admob_params["admob_site_id"]
	
	# Meta Parameters.
	#admob_post["u"] = request.META.get("HTTP_USER_AGENT", None)
	admob_post["u"] = request.get("HTTP_USER_AGENT")
	#admob_post["i"] = request.META.get("REMOTE_ADDR", None)
	admob_post["i"] = request.get("REMOTE_ADDR")
	#admob_post["p"] = request.build_absolute_uri()
	admob_post["p"] = request.url
	admob_post["t"] = md5(request.session.session_key).hexdigest()
	
	# Hardcoded Parameters.
	admob_post["e"] = "UTF-8"
	admob_post["v"] = admob_version

	# Optional Parameters.
	admob_post["ma"] = admob_params.get("admob_markup", None)
	admob_post["d[pc]"] = admob_params.get("admob_postal_code", None)
	admob_post["d[ac]"] = admob_params.get("admob_area_code", None)
	admob_post["d[coord]"] = admob_params.get("admob_coordinates", None)
	admob_post["d[dob]"] = admob_params.get("admob_dob", None)
	admob_post["d[gender]"] = admob_params.get("admob_gender", None)
	admob_post["k"] = admob_params.get("admob_keywords", None)
	admob_post["search"] = admob_params.get("admob_search", None)
	
	#for k, v in request.META.items():
	for k, v in request.get_all():
		if k not in admob_ignore:
			admob_post["h[%s]" % k] = v
			
	# Strip all ``None`` and empty values from admob_post.
	for k, v in admob_post.items():
		if v is None or v == "":
			admob_post.pop(k)

	if admob_mode == "test":
		admob_post["m"] = "test"

	# Request the Ad.
	admob_success = True
	try:
		admob_data = urlencode(admob_post)
		#admob_file = urlopen(admob_endpoint, admob_data)
		#admob_contents = admob_file.read()
		#admob_contents = urlfetch.fetch(url=admob_endpoint)
		admob_contents = urlfetch.fetch(url="http://r.admob.com/ad_source.php")
		self.response.out.write(admob_endpoint)
		self.response.out.write(admob_data)
		if admob_contents is None or admob_contents == "":
			admob_success = False
	except Exception, e:
		admob_success = False
	
	if not admob_success:
		admob_contents = "<img src=\"http://t.admob.com/li.php/c.gif/%(admob_site_id)s/1/%(admob_timeout)F/%(absolute_uri)s\" alt=\"\" width=\"1\" height=\"1\" />"  \
			% {"admob_site_id" : admob_params["admob_site_id"], 
				 "admob_timeout" : admob_timeout, 
				 #"absolute_uri" : md5(request.build_absolute_uri()).hexdigest()}
				 "absolute_uri" : md5(request.url).hexdigest()}
				 
	# DEBUG:
	# print 'Connecting to: %s' % admob_endpoint
	# print 'Sending Parameters:'
	# print admob_post
	# print 'Got reponse:'
	# print admob_contents
				 
	return admob_contents
